const fs = require('fs');

module.exports = {
  // 传入文件夹的路径看是否存在，存在不用管，不存在则直接创建文件夹
  checkDirExist: ((p) => {
    if (!fs.existsSync(p)) {
      fs.mkdirSync(p);
    }
  }),

  //获取路径文件信息(文件名、后缀名)
  getFileInfo: ((filePath, key) => {
    filePath = filePath.split('?')[0]; //去参数
    var re = /([^\.\/\\]+)\.([a-z]+)$/i,
      resultArr = re.exec(filePath),
      info = {};
    if (resultArr) {
      info.name = resultArr[1];
      info.type = resultArr[2];
    }
    return key ? info[key] : info;
  }),

  mergeFile: ((filePath, newPath) => {
    return new Promise((resolve, reject) => {
      let files = fs.readdirSync(filePath);
      filesArray = []
      files.forEach(el => {
        filesArray.push({ file: el, sortNum: el.split('_')[1] })
      })
      let newFile = fs.createWriteStream(newPath);
      let filesArr = filesArray.sort(function (a, b) { return a.sortNum - b.sortNum });
      main();
      function main (index = 0) {
        let currentFile = filePath + '/' + filesArr[index].file;
        let stream = fs.createReadStream(currentFile);
        stream.pipe(newFile, { end: false });
        stream.on('end', function () {
          if (index < filesArr.length - 1) {
            index++;
            main(index);
          } else {
            resolve({ code: 200 });
          }
        })
        stream.on('error', function (error) {
          reject({ code: 102, data: { error } })
        })
      }

    })
  })
}